<template>
  <div class="home">
    <!-- 筛选 -->
    <div class="search_content">
      <van-nav-bar :title="$route.meta.title" left-text="返回" left-arrow @click-left="goBack" />
      <form action>
        <van-search v-model="requestParams.customerOrPhone" placeholder="请输入客户名称或联系电话" shape="round" @search="initData" @clear="clearSearch" />
      </form>
      <div class="search_item">
        <van-dropdown-menu :close-on-click-outside="false">
          <van-dropdown-item title="品牌展厅" ref="brandRef">
            <div class="searchbox timebox">
              <van-field v-model="requestParams.brandName" name="品牌" label="品牌" placeholder="请选择" input-align="right" :rules="[{ required: true }]" right-icon="arrow" @click="handleSelect('brandId', 'brandName')" readonly />
              <van-field v-model="requestParams.showOrgName" name="展厅" label="展厅" input-align="right" placeholder="请选择" :rules="[{ required: true }]" right-icon="arrow" @click="handleSelect('showOrgId', 'showOrgName')" readonly />
              <div class="insureBtn">
                <van-button size="small" type="warning" class="resetBtn" @click="handleBrandReset()">重置</van-button>
                <van-button size="small" type="info" class="confirmBtn" @click="onConfirm('brandRef')">确认</van-button>
              </div>
            </div>
          </van-dropdown-item>
          <van-dropdown-item title="状态" ref="statusRef">
            <div class="searchbox">
              <div class="title">线索状态</div>
              <div class="insureList">
                <div class="insure_item" :class="item.check ? 'active' : ''" v-for="(item, index) in leadsBillStatusList" :key="index" @click="handleSearchSelect(index, 'leadsBillStatusList')">{{ item.name }}</div>
              </div>
              <div class="title">跟进状态</div>
              <div class="insureList">
                <div class="insure_item" :class="item.check ? 'active' : ''" v-for="(item, index) in followBillStatusList" :key="index" @click="handleSearchSelect(index, 'followBillStatusList')">{{ item.name }}</div>
              </div>
              <div class="title">评估状态</div>
              <div class="insureList">
                <div class="insure_item" :class="item.check ? 'active' : ''" v-for="(item, index) in estimateBillStatusList" :key="index" @click="handleSearchSelect(index, 'estimateBillStatusList')">{{ item.name }}</div>
              </div>

              <div class="insureBtn">
                <van-button size="small" type="warning" class="resetBtn" @click="handleSearchReset()">重置</van-button>
                <van-button size="small" type="info" class="confirmBtn" @click="onConfirm('statusRef')">确认</van-button>
              </div>
            </div>
          </van-dropdown-item>

          <van-dropdown-item title="线索来源" ref="filterRef">
            <div class="searchbox">
              <div class="insureList">
                <div class="insure_item" :class="item.check ? 'active' : ''" v-for="(item, index) in leadsSourceList" :key="index" @click="handleSearchSelect(index, 'leadsSourceList')">{{ item.name }}</div>
              </div>
              <div class="insureBtn">
                <van-button size="small" type="warning" class="resetBtn" @click="handleSearchXsReset()">重置</van-button>
                <van-button size="small" type="info" class="confirmBtn" @click="onConfirm('filterRef')">确认</van-button>
              </div>
            </div>
          </van-dropdown-item>

          <van-dropdown-item title="筛选" ref="detailRef">
            <div class="searchbox timebox">
              <div class="title">线索提交时间</div>
              <div class="flex">
                <van-field class="time_item" v-model="requestParams.taskStartCreateTime" label :placeholder="'开始时间'" input-align="right" readonly @click="handleSelectTime('taskStartCreateTime')" />-
                <van-field class="time_item" v-model="requestParams.taskEndCreateTime" label :placeholder="'结束时间'" input-align="right" readonly @click="handleSelectTime('taskEndCreateTime')" />
              </div>
              <van-form>
                <van-field v-model="requestParams.leasdProvicePersonName" label="线索提供人" :placeholder="'请输入'" input-align="right" />
                <van-field v-model="requestParams.leasdFollowPersonName" label="线索跟进人" :placeholder="'请输入'" input-align="right" />
              </van-form>

              <div class="insureBtn">
                <van-button size="small" type="warning" class="resetBtn" @click="handleAccidentReset()">重置</van-button>
                <van-button size="small" type="info" class="confirmBtn" @click="onConfirm('detailRef')">确认</van-button>
              </div>
            </div>
          </van-dropdown-item>
        </van-dropdown-menu>

        <!-- 服务顾问下拉 -->
        <van-popup v-model="showSelectPicker" position="bottom">
          <van-picker show-toolbar :columns="columns" @confirm="handleSelectConfirm" @cancel="showSelectPicker = false" value-key="name" />
        </van-popup>
        <!-- 时间选择 -->
        <van-popup v-model="showPickerDate" position="bottom">
          <van-datetime-picker v-model="currentDate" type="date" @cancel="onCancelDate" @confirm="onConfirmDate" :formatter="formatter" />
        </van-popup>
      </div>
    </div>

    <!-- 列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="loadData" v-if="recordList && recordList.length != 0">
        <div class="orderList">
          <div class="flex" v-for="(item, index) in recordList" :key="index">
            <div class="taskCheck" v-if="showTransmitFlag">
              <van-checkbox v-model="item.check" shape="square" icon-size="15px"></van-checkbox>
            </div>
            <div class="orderItem">
              <div class="orderItem_header">
                <div class="orderItem_lt" @click="goDetail(item)">
                  <div class="carNo">{{ item.customerName }}</div>
                </div>
                <div class="orderItem_rt">跟进人：{{ item.followName ? item.followName : '-' }}</div>
              </div>
              <div class="orderItem_content" @click="goDetail(item)">
                <div class="orderItem_data full">
                  <div class="order_label">车型</div>
                  <div class="txt">{{ item.carModelName ? item.carModelName : '-' }}</div>
                </div>
                <div class="orderItem_data full">
                  <div class="order_label">展厅</div>
                  <div class="txt">{{ item.showOrgName ? item.showOrgName : '-' }}</div>
                </div>
                <div class="orderItem_data">
                  <div class="order_label">线索来源</div>
                  <div class="txt">{{ item.leadsSource ? item.leadsSource : '-' }}</div>
                </div>
                <div class="orderItem_data">
                  <div class="order_label">创建时间</div>
                  <div class="txt">{{ item.bizDate ? item.bizDate : '-' }}</div>
                </div>
                <div class="orderItem_data">
                  <div class="order_label">线索提供人</div>
                  <div class="txt">{{ item.provideName ? item.provideName : '-' }}</div>
                </div>
                <div class="orderItem_data">
                  <div class="order_label">下次跟进时间</div>
                  <div class="txt">{{ item.nextFollowTime ? item.nextFollowTime : '-' }}</div>
                </div>
              </div>
              <div class="orderItem_footer">
                <div class="orderItem_status" v-if="item.followBillStatus">{{ item.followBillStatus }}</div>
                <div class="orderItem_status" v-if="item.leadsBillStatus">{{ item.leadsBillStatus }}</div>
              </div>
            </div>
          </div>
        </div>
      </van-list>
      <van-empty class="noContent" description="暂无数据" v-else />
    </van-pull-refresh>

    <div class="addBtn">
      <div class="footerBtn orderItem_filebox" @click="handleAdd">新增线索</div>
    </div>
  </div>
</template>

<script>
import { Search, DropdownMenu, DropdownItem, Empty, Dialog } from "vant";
import taskApi from "@/api/taskApi";
import commonApi from "@/api/commonApi";
import { getCookies } from "@/utils/util.js";
import sellManageApi from "@/api/sellManageApi";

export default {
  name: "repairOrder",
  components: {
    Search,
    DropdownMenu,
    DropdownItem,
    Empty,
    Dialog
  },
  data() {
    return {
      value: "",
      carCouponList: [
        { name: "是", code: 1, check: false },
        { name: "否", code: 0, check: false }
      ],
      taskTypeList: [],
      statusList: [
        { name: "已处理", code: 1, check: false },
        { name: "未处理", code: 2, check: false }
      ],

      recordList: [
        // {
        //   billId: '', //单据ID
        //   customerName: '章三', //客户名称
        //   phone: '18123123', //客户电话
        //   carModelName: '阿迪', // 车型
        //   leadsBillStatus: '跟进', //线索状态
        //   followBillStatus: '跟进', //跟进状态
        //   followName: '章三啊', //线索跟进人
        //   provideName: '章三啊', // 线索提供人
        //   bizDate: '2020-09-09', // 创建日期
        //   nextFollowTime: '2020-09-09', //下次跟进日期
        // },
      ],
      columns: [],
      showSelectPicker: false,
      requestParams: {
        customerOrPhone: "", //客户名称或联系电话,非必填，String
        pageNo: 1, //页码，必填，int
        orgId: "", //登录组织ID,必填，String
        leadsBillStatus: "", //线索状态，非必填，String
        followBillStatus: "", //跟进状态，非必填，String
        estimateBillStatus: "", //评估状态，非必填，String
        leadsStartDate: "", //线索提交开始时间，非必填，String
        leadsEndDate: "", //线索提交结束时间，非必填，String
        leasdFollowPersonName: "", //线索跟进人，非必填，String
        leasdProvicePersonName: "", //线索提供人，非必填，String
        leadsSource: "",
        userId: getCookies("userId"), //用户ID，必填，String
        brandName: "",
        showOrgName: ""
      },
      carCouponIndex: null,

      repairCenterList: [
        { name: "厦门路虎", code: 1 },
        { name: "厦门捷豹", code: 2 }
      ],
      serviceList: [
        { name: "黄某某", code: 1 },
        { name: "张某某", code: 2 }
      ],
      delayList: [
        { name: "是", billId: 1, check: false },
        { name: "否", billId: 0, check: false }
      ],
      creatList: [
        { name: "是", billId: 1, check: false },
        { name: "否", billId: 0, check: false }
      ],
      defeatList: [
        { name: "是", billId: 1, check: false },
        { name: "否", billId: 0, check: false }
      ],

      delayIndex: null,
      creatIndex: null,
      defeatIndex: null,
      showTransmitFlag: false,
      timeField: "",
      showPickerDate: false,
      currentDate: new Date(),
      list: [],
      // 分页参数
      loading: false,
      finished: false,
      refreshing: false,
      isLoadData: false,

      field: "",
      fieldName: "",
      fixCenterList: [],
      twoBillStatusList: [],
      leadsBillStatusList: [],
      followBillStatusList: [],
      estimateBillStatusList: [],
      leadsSourceList: []
    };
  },

  mounted() {
    this.getLeadsBillStatus();
    this.getFollowBillStatus();
    this.getEstimateBillStatus();
    this.getLeadsSource();
    this.getEmpPerson();
    this.initData();
  },

  watch: {
    $route: {
      handler: function(val, oldVal) {
        if (val && val.query && val.query.type) {
          this.initData();
        }
      },
      deep: true,
      immediate: false
    }
  },

  methods: {
    // 初始化列表
    initData() {
      this.requestParams.pageNo = 1;
      this.loadData();
    },
    // 获取列表
    loadData() {
      if (this.isLoadData) return;
      this.isLoadData = true;
      this.loading = true;
      this.finished = false;
      // console.log(this.isLoadData);
      sellManageApi
        .secondHandCarFacade({
          ...this.requestParams,
          method: "getPurchaseLeadsList"
        })
        .then(res => {
          if (!this.recordList || this.recordList.length < 1) {
            this.getBrandByUser();
          }
          if (this.requestParams.pageNo == 1) {
            this.recordList = res.data || [];
          } else {
            this.recordList = this.recordList.concat(res.data || []);
          }
          this.requestParams.pageNo += 1;

          if (res.data && res.data.length < 10) {
            this.finished = true;
            this.isLoadData = true;
          }
          this.isLoadData = false;
          this.loading = false;
        });
    },
    // 下拉刷新
    onRefresh() {
      // 清空列表数据
      this.recordList = [];
      this.finished = false;
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      this.refreshing = false;
      this.initData();
    },
    // 获取服务顾问
    getEmpPerson() {
      commonApi
        .getEmpPerson({
          fixCenterId: "",
          userId: this.requestParams.userId
        })
        .then(res => {
          this.serviceList = res.data;
        });
    },
    // 获取线索状态
    getLeadsBillStatus() {
      commonApi
        .getEnums({ key: "leadsBillStatus", userId: this.requestParams.userId })
        .then(res => {
          if (res.data) {
            this.leadsBillStatusList = this.formatCheckData(res.data);
          }
        });
    },
    // 获取线索跟进状态
    getFollowBillStatus() {
      commonApi
        .getEnums({
          key: "followBillStatus",
          userId: this.requestParams.userId
        })
        .then(res => {
          if (res.data) {
            this.followBillStatusList = this.formatCheckData(res.data);
          }
        });
    },
    // 获取评估状态
    getEstimateBillStatus() {
      commonApi
        .getEnums({
          key: "estimateBillStatus",
          userId: this.requestParams.userId
        })
        .then(res => {
          if (res.data) {
            this.estimateBillStatusList = this.formatCheckData(res.data);
          }
        });
    },
    // 获取线索来源
    getLeadsSource() {
      commonApi
        .getEnums({
          key: "leadsSource",
          userId: this.requestParams.userId
        })
        .then(res => {
          if (res.data) {
            this.leadsSourceList = this.formatCheckData(res.data);
          }
        });
    },
    // 获取品牌
    getBrandByUser() {
      sellManageApi
        .secondHandCarFacade({
          userId: this.userId,
          orgKey: "brandAll", // orgkey
          method: "getShowOrgByUser"
        })
        .then(res => {
          if (res.data) {
            this.brandList = res.data;
          }
        });
    },
    // 获取展厅
    getShowOrgByUser() {
      sellManageApi
        .secondHandCarFacade({
          userId: this.userId,
          method: "getShowOrgByBandId",
          brandId: this.requestParams.brandId
        })
        .then(res => {
          if (res.data) {
            this.showOrgList = res.data;
          }
        });
    },

    // 格式化多选数据
    formatCheckData(data) {
      data.forEach(item => {
        item.check = false;
      });
      return data;
    },

    // 选择下拉
    handleSelect(field, fieldName) {
      this.showSelectPicker = true;
      if (field == "showOrgId") {
        this.columns = this.showOrgList;
      } else if (field == "brandId") {
        this.columns = this.brandList;
      }
      this.field = field;
      this.fieldName = fieldName;
    },

    // 品牌展厅重置
    handleBrandReset() {
      this.requestParams.brandId = "";
      this.requestParams.brandName = "";
      this.handleHallReset();
    },
    // 品牌展厅重置
    handleHallReset() {
      this.requestParams.showOrgId = "";
      this.requestParams.showOrgName = "";
    },

    // 选择下拉确认
    handleSelectConfirm(value, index) {
      this.requestParams[this.field] = value.billId;
      this.requestParams[this.fieldName] = value.name;
      if (this.field == "brandId") {
        this.getShowOrgByUser();
        this.handleHallReset();
      }
      this.showSelectPicker = false;
    },

    //时间重置
    handleAccidentReset() {
      this.requestParams.leasdProvicePersonName = "";
      this.requestParams.leasdFollowPersonName = "";
      this.requestParams.leadsEndDate = "";
      this.requestParams.leadsStartDate = "";
    },
    onConfirm(ref) {
      this.$refs[ref].toggle();
      if (ref == "statusRef") {
        this.requestParams.leadsBillStatus = this.getCheckData(
          this.leadsBillStatusList
        ).join(";");
        this.requestParams.followBillStatus = this.getCheckData(
          this.followBillStatusList
        ).join(";");
        this.requestParams.estimateBillStatus = this.getCheckData(
          this.estimateBillStatusList
        ).join(";");
      }
      if (ref == "filterRef") {
        this.requestParams.leadsSource = this.getCheckData(
          this.leadsSourceList
        ).join(";");
      }
      this.initData();
    },
    // 获取选中的数据
    getCheckData(list) {
      let checkList = [];
      list.forEach(el => {
        if (el.check) {
          checkList.push(el.value);
        }
      });
      return checkList;
    },
    // 时间确认
    onConfirmDate() {
      this.requestParams[
        this.timeField
      ] = `${this.value1}-${this.value2}-${this.value3}`; // 字符串拼接 结果入2020-07-03
      this.onCancelDate();
    },
    onCancelDate() {
      this.showPickerDate = false;
    },

    // 日期组件自定义格式
    formatter(type, value) {
      if (type === "year") {
        this.value1 = value; // 可以拿到当前点击的数值
        return `${value}年`;
      } else if (type === "month") {
        this.value2 = value;
        return `${value}月`;
      }
      this.value3 = value;
      return `${value}日`;
    },

    // 获取list名称
    getFieldName(list, key, val) {
      if (list && list.length > 0) {
        let obj = list.filter(item => {
          return item[key] == val;
        });
        if (obj.length > 0) {
          return obj[0].name;
        }
      }
      return null;
    },

    // 详情
    goDetail(data) {
      localStorage.setItem("billId", data.billId);
      this.$router.push({
        path: "/assessManageDetail"
        // query: { billId: data.billId },
      });
    },
    // 新增
    handleAdd() {
      this.$router.push({
        path: "/assessManageEdit"
      });
    },
    // 顶部筛选选择数据
    handleSearchSelect(index, listKey) {
      this[listKey][index].check = !this[listKey][index].check;
    },
    // 重置
    handleSearchReset() {
      this.leadsBillStatusList.forEach(item => {
        item.check = false;
      });
      this.followBillStatusList.forEach(item => {
        item.check = false;
      });
      this.estimateBillStatusList.forEach(item => {
        item.check = false;
      });
    },
    // 线索重置
    handleSearchXsReset() {
      this.leadsSourceList.forEach(item => {
        item.check = false;
      });
    },

    // 是否数据选择
    handleIsSelect(index, key, list, field) {
      this[key] = index;
      this.requestParams[field] = this[list][index].billId;
    },
    // 任务转交展示
    handleShowTransmit() {
      this.showTransmitFlag = true;
    },
    // 确认转交
    handleTransmitSubmit() {},
    // 取消
    handleTransmitCancel() {
      this.showTransmitFlag = false;
    },
    // 时间筛选
    handleSelectTime(field) {
      this.timeField = field;
      this.showPickerDate = true;
    },
    clearSearch() {
      this.requestParams.customerOrPhone = "";
      this.initData();
    },
    goBack() {
      localStorage.setItem("skipUrl", "");
      this.$router.push("/home");
    }
  }
};
</script>

<style lang="less" scoped="">
body {
  background: #f3f3f3;
}
.search_content {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 2;
}
.timebox {
  /deep/.van-cell::after {
    border: none;
  }
  .time_item {
    /deep/.van-field__control--right {
      border: 1px solid #d1d1d1;
      padding: 5px 0;
      text-align: center;
      border-radius: 3px;
    }
  }
}
.full {
  width: 100% !important;
}
.searchbox {
  padding: 15px;
  .title {
    font-size: 15px;
    font-weight: bold;
    color: #333;
    margin-bottom: 10px;
    padding-top: 10px;
  }
  .insureList {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    .insure_item {
      border: 1px solid #999;
      text-align: center;
      padding: 7px 0rem;
      width: 30%;
      box-sizing: border-box;
      // margin-right:5px;
      font-size: 13px;
      border-radius: 3px;
      color: #666;
      margin-bottom: 10px;
      margin-right: 5%;
      &:nth-child(3n) {
        margin-right: 0;
      }
      &.active {
        border: 1px solid #f65e07;
        color: #f65e07;
      }
    }
  }
  .insureBtn {
    display: flex;
    justify-content: right;
    margin-top: 20px;
    .resetBtn {
      padding: 0 20px;
      margin-right: 10px;
    }
    .confirmBtn {
      padding: 0 20px;
    }
  }
}

.orderList {
  padding-top: 148px;
  margin: 10px;
  overflow: hidden;
  // width: 100%;
  // padding-bottom: 1.5rem;
  .taskCheck {
    margin-right: 5px;
  }
  .orderItem {
    padding: 15px;
    background: #fff;
    border-radius: 10px;
    margin-bottom: 15px;
    width: 100%;

    .orderItem_header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #f6f6f6;
      position: relative;
      .orderItem_lt {
        .carNo {
          font-size: 15px;
          color: #333;
          margin-right: 10px;
          font-weight: bold;
        }

        .carStatus {
          background: #35bc04;
          color: #fff;
          border-radius: 4px;
          padding: 5px 10px;
          font-size: 12px;
          text-align: center;
          width: 50px;
          margin-top: 5px;
        }
      }
      .orderItem_rt {
        display: flex;
        align-items: center;
        align-self: center;
        justify-content: flex-start;
        color: #666;
        font-size: 14px;

        .txt {
          font-size: 14px;
          color: #161616;
        }
        .icon-tel {
          color: #fff;
          background: #35bc04;
          font-size: 16px;
          padding: 5px;
          border-radius: 50%;
          margin-right: 10px;
        }
        .icon-wx {
          color: #409eff;
          font-size: 32px;
        }
      }
    }
    .orderItem_content {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      align-items: center;
      .orderItem_data {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        width: 50%;
        margin-bottom: 10px;
        font-size: 14px;
        box-sizing: content-box;
        color: #333;
        .order_label {
          font-size: 14px;
          color: #999;
          margin-right: 5px;
        }
        .txt {
          font-size: 14px;
          color: #333;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        &.time {
          width: 100%;
        }
      }
    }
    .orderItem_footer {
      display: flex;
      justify-content: space-between;
      border-top: 1px solid #f6f6f6;
      padding-top: 10px;
      .orderItem_status {
        background: #35bc04;
        color: #fff;
        font-size: 12px;
        padding: 0.08rem 0.15rem;
        border-radius: 3px;
      }
    }
    .orderItem_file {
      background: #ebebeb;
      color: #333;
      border-radius: 5px;
      padding: 10px 0;
      text-align: center;
      width: 100%;
      font-size: 14px;
      display: flex;
      align-items: center;
      justify-content: center;
      .file_item {
        width: 33.33%;
        border-right: 1px solid #ccc;
        .icon-tel {
          font-size: 17px;
          color: #35bc04;
          margin-right: 5px;
        }
        .icon-mileage {
          font-size: 20px;
          color: #409eff;
          margin-right: 5px;
          position: relative;
          top: 2px;
        }
        .icon-gw {
          font-size: 20px;
          color: #409eff;
          margin-right: 5px;
          position: relative;
          top: 2px;
        }
        &:last-child {
          border: none;
        }
      }
    }
  }
}
.addBtn {
  position: fixed;
  bottom: 40px;
  width: 100%;
  z-index: 1;
  .footerBtn {
    width: 120px;
    margin: auto;
    text-align: center;
    font-size: 14px;
    padding: 10px 0;
    border-radius: 50px;
  }
  .orderItem_filebox {
    margin: auto;
    background: #409eff;
    color: #fff;
  }
  .comfirmBtn {
    background: #409eff;
    color: #fff;
  }
  .cancelBtn {
    border: 1px solid #ccc;
    color: #999;
    background: #fff;
  }
}
.noContent {
  margin-top: 100px;
}
</style>
